import type { APIResponse } from '@/types/utils'
import axios, {
  type AxiosInstance,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from 'axios'

import { ElMessage } from 'element-plus'

const http: AxiosInstance = axios.create({
  // 基地址
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时时间
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// 请求拦截器
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('TOKEN')
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.status === -1) {
      ElMessage({ type: 'error', message: response.data.message })
      return Promise.reject(response.data.message)
    }

    return response.data
  },
  (err) => {
    if (err && err.response) {
      let message = ''
      const status = err.response.status
      switch (status) {
        case 401:
          message = '登录过期'
          break
        case 403:
          message = '无权访问'
          break
        case 404:
          message = '地址错误'
          break
        case 500:
          message = '服务器故障'
          break
        default:
          message = '网络问题'
          break
      }
      ElMessage({
        type: 'error',
        message
      })
    }

    return Promise.reject(err)
  }
)

export const get = <T>(url: string, params?: any) => {
  return http.get<T, APIResponse<T>>(url, params)
}

export const post = <T>(url: string, data?: any) => {
  return http.post<T, APIResponse<T>>(url, data)
}
